<template>
  <div>
    <div id="map-container">
      <div id="top-bar">
        <button id="back-button" @click="navigateBack">返回首页</button>
        <el-button type="primary" size="medium" @click="openMainDialog" icon="el-icon-plus" round plain
          style="margin-left: 10px;">
          添加美食
        </el-button>
      </div>
      <div id="map" ref="mapDOM"></div>
    </div>

    <!-- 主弹窗 -->
    <el-dialog :visible.sync="mainDialogVisible" title="添加美食至分组" width="50%" :close-on-click-modal="false" top="40px">
      <el-form :inline="true">
        <el-form-item label="选择分组">
          <el-select v-model="chooseGroup" placeholder="请选择组别">
            <el-option v-for="group in foodGroups" :key="group.name" :label="group.name"
              :value="group.name"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <el-input v-model="searchQuery" placeholder="搜索美食" clearable style="width: 100%; margin-bottom: 20px;" />

      <div class="scrollable-food-list">
        <ul>
          <li v-for="shop in filteredShops" :key="shop.name" class="shop-item">
            <span>{{ shop.name }}</span>
            <el-button type="primary" size="mini" @click="addToGroup(shop.name)"
              v-if="!isFoodInCurrentGroup(shop.name)">
              添加
            </el-button>
            <el-button type="danger" size="mini" @click="removeFood(shop.name)" v-else>
              删除
            </el-button>
          </li>
        </ul>
      </div>
      <div class="food-list">
        <h4>当前组别：{{ chooseGroup }}</h4>
        <el-input v-model="searchFood" placeholder="搜索组别美食" clearable style="width: 100%; margin-bottom: 20px;" />
        <el-tag v-for="(food, index) in filteredFoods" :key="index" closable @close="removeFood(food)"
          style="margin: 5px;">
          {{ food }}
        </el-tag>
      </div>

    </el-dialog>
  </div>
</template>

<script>
  import AMapLoader from "@amap/amap-jsapi-loader";
  import { mapGetters, mapMutations } from "vuex";
  import {shopData} from '@/assets/foodData/BaoLongFoodData.js'

  export default {
    name: "BaolongSnackMap",
    data() {
      return {
        shopData,
        map: null,
        chooseGroup: "",
        mainDialogVisible: false,
        searchQuery: "",
        searchFood: "",
        // infoWindow: null
      };
    },
    computed: {
      ...mapGetters(["foodGroups", "selectedGroup", "selectedGroupFoods"]),
      filteredShops() {
        return this.shopData.filter((shop) =>
          shop.name.toLowerCase().includes(this.searchQuery.toLowerCase())
        );
      },
      filteredFoods() {
        return this.selectedGroupFoods.filter(food => food.includes(this.searchFood))
      }
    },
    watch: {
      chooseGroup(newGroup) {
        this.updateSelectedGroup(newGroup)
      }
    },
    methods: {
      ...mapMutations(["deleteFoodFromGroup", "updateSelectedGroup"]),
      isFoodInCurrentGroup(foodName) {
        const group = this.foodGroups.find((g) => g.name === this.chooseGroup);
        return group ? group.foods.includes(foodName) : false;
      },
      removeFood(foodName) {
        this.deleteFoodFromGroup({
          groupName: this.chooseGroup,
          food: foodName
        });
        this.$message.success(`已从分组 ${this.chooseGroup} 删除 ${foodName}！`);
      },
      navigateBack() {
        this.$router.push("/");
      },
      openMainDialog() {
        this.searchQuery="";
        this.mainDialogVisible = true;
      },
      addToGroup(shopName, groupName = this.chooseGroup) {
        if (!groupName) {
          this.$message.error("请先选择一个分组");
          return;
        }
        this.$store.commit("addFoodToGroup", {
          groupName,
          food: shopName
        });
        this.$message.success(`已将 ${shopName} 添加到分组 ${groupName}`);
      },
      initializeMap() {
        AMapLoader.load({
          key: "0cbff43837a69935983f7c73d0172d35",
          version: "2.0"
        })
          .then((AMap) => {
            this.map = new AMap.Map(this.$refs["mapDOM"], {
              zoom: 18,
              center: [120.384606, 30.312443],
              viewMode: "2D",
              dragEnable: false,
              zoomEnable: false,
              rotateEnable: false
            });

            // this.infoWindow = new AMap.InfoWindow({
            //   isCustom: true,
            //   offset: new AMap.Pixel(0, -40)
            // });

            this.addMarkers(AMap);
          })
          .catch((e) => console.error("高德地图加载失败：", e));
      },
      addMarkers(AMap) {
        const logo = require('@/assets/mark_bs.png');
        this.shopData.forEach((shop) => {
          const markerContent = `
								<div class="custom-content-marker" style="position: relative; text-align: center;">
									<img src="${logo}" style="display: block; margin: 0 auto; width: 19px; height: 31.5px;">
								</div>
							`;
          const marker = new AMap.Marker({
            position: new AMap.LngLat(shop.longitude, shop.latitude),
            content: markerContent,
						offset: new AMap.Pixel(-9.5, -29.5),
            title: shop.name
          });

          marker.on("click", () => {
            this.searchQuery=shop.name;
            this.mainDialogVisible=true;
            
          //   const groupOptions = this.foodGroups
          //     .map(
          //       (group) =>
          //         `<option value="${group.name}" ${group.name === this.selectedGroup ? "selected" : ""} >${group.name}</option>`
          //     )
          //     .join("");
          //   const content = `
          //   <div style="
          //     padding: 10px; 
          //     background: #fff; 
          //     border: 1px solid #ccc; 
          //     border-radius: 5px;
          //     box-shadow: 0 2px 10px rgba(0,0,0,0.3);
          //     text-align: center;
          //     position: relative;">
          //       <button 
          //         style="
          //           position: absolute; 
          //           top: 5px; 
          //           right: 5px; 
          //           background: transparent; 
          //           border: none; 
          //           font-size: 16px; 
          //           cursor: pointer;"
          //         onclick="window.closeInfoWindow()">
          //         ×
          //       </button>
          //       <div style="margin-bottom: 5px;">${shop.name}</div>
          //       <select id="info-window-group" style="margin-bottom: 5px; width: 100%;">
          //         ${groupOptions}
          //       </select>
          //       <button 
          //         style="background-color: #007bff; color: white; border: none; padding: 5px 10px; border-radius: 3px; cursor: pointer;"
          //         onclick="window.addShopToGroup('${shop.name}')">
          //         添加
          //       </button>
          //   </div>
          // `;
          //   this.infoWindow.setContent(content);
          //   this.infoWindow.open(this.map, marker.getPosition());
          });

          this.map.add(marker);
        });

        window.addShopToGroup = (shopName) => {
          const groupSelect = document.getElementById("info-window-group");
          const selectedGroup = groupSelect ? groupSelect.value : "";
          this.addToGroup(shopName, selectedGroup);
        };
        window.closeInfoWindow = () => {
          if (this.infoWindow) {
            this.infoWindow.close();
          }
        };
      }
    },
    mounted() {
      this.initializeMap();
    },
    created(){
      this.chooseGroup = this.selectedGroup;
    }
  };
</script>

<style>
  #map-container {
    position: relative;
    width: 100vw;
    height: 100vh;
  }

  #top-bar {
    display: flex;
    align-items: center;
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 1000;
  }

  #back-button {
    background-color: #007bff;
    color: white;
    border: none;
    padding: 8px 15px;
    border-radius: 4px;
    cursor: pointer;
  }

  #map {
    width: 100%;
    height: 100%;
  }

  .shop-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }

  .scrollable-food-list {
    max-height: 300px;
    overflow-y: auto;
  }
</style>
